<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="(e) => {
          (searchlist = { ...e }), (currentPage = 1), getTableDataList();
        }
        ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>
    <template v-slot:table>
      <TableData :isSelect="true" :tableThead="tableThead" :dataList="dataList" @selection-change="selectionChange">
        <template v-slot:typeFlag="{ row }">
          <span>{{ row.typeFlag == 0 ? "订单入库" : "自行入库" }}</span>
        </template>
        <template v-slot:shouldArriveNum="{ row }">
          <span>{{ row.shouldArriveNum
            }}{{ row.unit ? row.unit.symbol || row.unit.unitName : '' }}</span>
        </template>
        <template v-slot:primaryQuantity="{ row }">
          <span>{{ row.primaryQuantity
            }}{{ row.unit ? row.unit.symbol || row.unit.unitName : '' }}</span>
        </template>
        <template v-slot:slotOperate="{ row }">
          <template v-if="!row.index">
            <el-button v-if="codeList.indexOf('edit') !== -1 && forderStatus === 0" class="text-btn-cursor" type="text"
              size="small" @click="edit(row, 'edit')">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button v-if="codeList.indexOf('revoke') !== -1 && forderStatus === 0" class="text-btn-cursor"
              type="text" size="small" @click="edit(row, 'check')">
              <i class="el-icon-edit-outline"></i>审核
            </el-button>
            <el-button v-if="codeList.indexOf('delete') !== -1 && forderStatus === 0"
              class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete([row])">
              <i class="el-icon-delete"></i> 删除
            </el-button>
            <el-button v-if="forderStatus !== 0" class="text-btn-cursor" type="text" size="small"
              @click="edit(row, 'check')">
              <i class="el-icon-view"></i>查看详情
            </el-button>
          </template>
        </template>
      </TableData>
      <!-- <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading" :listData="tableData"
        @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button v-if="judgePermission(76, 'edit') && forderStatus === 0" class="text-btn-cursor" type="text"
              size="small" @click="edit(row, 'check')">
              <i class="el-icon-edit-outline"></i> 审核
            </el-button>
            <el-button v-if="judgePermission(76, 'edit') && forderStatus === 0" class="text-btn-cursor" type="text"
              size="small" @click="edit(row, 'edit')">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button v-if="judgePermission(76, 'delete') && forderStatus === 0" class="text-btn-cursor cursor-delete"
              type="text" size="small" @click="handleDelete(row.warehousingEntryNo)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
            <el-button v-if="judgePermission(76, 'edit') && forderStatus !== 0" class="text-btn-cursor" type="text"
              size="small" @click="edit(row, 'check')">
              <i class="el-icon-view"></i>查看详情
            </el-button>
          </template>
        </template>
        <template v-slot:viewList="{ row }">
          <template v-if="!row.index">
            <el-button class="text-btn-cursor" type="text" size="small" @click="kookInfo(row.warehousingEntryNo)">
              <i class="el-icon-view"></i>查看到货明细
            </el-button>
          </template>
        </template>
        <template v-slot:typeFlag="{ row, item }">
          <template v-if="!row.index">
            {{ row[item.prop] ? '自行入库' : '订单入库' }}
          </template>
        </template>
        <template v-slot:castUnit="{ row, item }">
          <template v-if="!row.index">
            {{ row.shouldArriveNum }} {{ row[item.prop].symbol || row[item.prop].unitName }}
          </template>
        </template>
        <template v-slot:unit="{ row, item }">
          <template v-if="!row.index">
            {{ row.primaryQuantity }} {{ row[item.prop].symbol || row[item.prop].unitName }}
          </template>
        </template>
      </Table> -->
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="pageSize" @current-change="handleCurrentChange"
        :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false" :title="titleText" :visible.sync="dialogFormVisible" width="80%"
        @close="cancel('formData')">
        <el-form ref="formData" label-position="right" :model="formData" label-width="120px" :rules="rules"
          class="el-form">
          <el-form-item class="w100p" v-if="nowChanceStau === 'add'" label="入库形式 :">
            <el-button :type="typeFlag ? '' : 'primary'" @click="changeAddWays(0)">订单入库</el-button>
            <el-button :type="!typeFlag ? '' : 'primary'" @click="changeAddWays(1)">自行入库</el-button>
          </el-form-item>
          <el-form-item class="w100p" v-if="typeFlag === 0 && nowChanceStau === 'add'" label="源头单据类型 :"
            prop="sourceDocType" :rules="[
              {
                required: true,
                message: '源头单据类型不能为空',
                trigger: 'change',
              },
            ]">
            <el-select class="w100p" v-model="formData.sourceDocType" placeholder="请选择源头单据类型" clearable filterable>
              <el-option v-for="(items, indexs) in sourceDocTypeList" :key="indexs" :label="items.name"
                :value="items.value" />
            </el-select>
          </el-form-item>
          <el-form-item class="w100p" v-if="typeFlag === 0 && nowChanceStau === 'add'" label="源头单号 :" prop="sourceDocNo"
            :rules="[
              {
                required: true,
                message: '源头单明细号不能为空',
                trigger: 'change',
              },
            ]">
            <el-select class="w100p" v-model="formData.sourceDocNo" placeholder="请选择源头单号" clearable filterable
              @change="getOrderDetailList">
              <el-option v-for="(items, indexs) in sourceDocNoList" :key="indexs" :label="items.orderNo"
                :value="items.orderNo" />
            </el-select>
          </el-form-item>
          <el-form-item class="w100p" v-if="nowChanceStau === 'add' && typeFlag === 0" label="选择入库商品 :">
            <el-checkbox-group v-model="formData.arrivalGoodsList" @change="chooseGoods">
              <el-checkbox v-for="(items, indexs) in arrivalGoodsList" :key="indexs" :label="items">{{
                items.materialName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div class="orderDetail" v-for="(orderDetail, index) in formData.putInStorageList" :key="orderDetail.key">
            <div v-if="nowChanceStau === 'add'" class="goods w100p">
              入库货{{ index + 1 }}
            </div>
            <el-form-item class="w50p" label="入库货名 :" :prop="'putInStorageList.' + index + '.materialNo'" :rules="[
              {
                required: true,
                message: '入库货名不能为空',
                trigger: 'change',
              },
            ]">
              <el-select class="w100p" v-model="orderDetail.materialNo" placeholder="请选择入库货名称" clearable filterable
                :disabled="nowChanceStau === 'check'" @change="getGoods($event, index)">
                <el-option v-for="(items, indexs) in materialList" :key="indexs" :label="items.materialName"
                  :value="items.materialNo" />
              </el-select>
            </el-form-item>
            <el-form-item class="w50p" label="入库类型 :" :prop="'putInStorageList.' + index + '.warehousingType'" :rules="[
              {
                required: true,
                message: '入库类型不能为空',
                trigger: 'change',
              },
            ]">
              <el-select class="w100p" filterable v-model="orderDetail.warehousingType" placeholder="请选择入库类型" clearable
                :disabled="nowChanceStau === 'check'">
                <el-option v-for="(items, indexs) in warehousingTypeList" :key="indexs" :label="items.name"
                  :value="items.name" />
              </el-select>
            </el-form-item>
            <el-form-item class="w50p" label="入货仓库 :" :prop="'putInStorageList.' + index + '.stordocNo'" :rules="[
              {
                required: true,
                message: '入货仓库不能为空',
                trigger: 'change',
              },
            ]">
              <el-select class="w100p" v-model="orderDetail.stordocNo" placeholder="请选择入货仓库" clearable filterable
                :disabled="nowChanceStau === 'check'">
                <el-option v-for="(items, indexs) in stordocList" :key="indexs" :label="items.stordocName"
                  :value="items.stordocNo" />
              </el-select>
            </el-form-item>
            <el-form-item class="w50p" label="批号 :" :prop="'putInStorageList.' + index + '.lotNumber'"
              :rules="[{ required: true, message: '批号', trigger: 'change' }]">
              <el-input class="w100p" v-model="orderDetail.lotNumber" clearable placeholder="请输入批号"
                :disabled="nowChanceStau === 'check'" />
            </el-form-item>
            <el-form-item class="w50p" label="单位 :" :prop="'putInStorageList.' + index + '.castUnitNo'" :rules="[
              { required: true, message: '单位不能为空', trigger: 'change' },
            ]">
              <el-select class="w100p" v-model="orderDetail.castUnitNo" placeholder="请选择单位" clearable filterable
                :disabled="nowChanceStau === 'check'" @change="exchangeRateToNull($event, index)">
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>
            <el-form-item class="w50p" label="应到数量 :" :prop="'putInStorageList.' + index + '.shouldArriveNum'" :rules="[
              { required: true, message: '数量不能为空', trigger: 'blur' },
              {
                pattern: /^\d+$/,
                message: '值该为正整数',
                trigger: ['change', 'blur'],
              },
            ]">
              <el-input class="w100p" v-model="orderDetail.shouldArriveNum" clearable placeholder="请输入应到数量"
                :disabled="nowChanceStau === 'check'">
                <template slot="append">
                  <span v-show="items.unitNo == orderDetail.castUnitNo" v-for="(items, indexs) in unitList"
                    :key="indexs">
                    {{ items.symbol || items.unitName }}
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="w50p" label="实收数量 :" :prop="'putInStorageList.' + index + '.arriveNum'" :rules="[
              { required: true, message: '数量不能为空', trigger: 'blur' },
              {
                pattern: /^\d+$/,
                message: '值该为正整数',
                trigger: ['change', 'blur'],
              },
            ]">
              <el-input class="w100p" v-model="orderDetail.arriveNum" clearable placeholder="请输入数量"
                :disabled="nowChanceStau === 'check'">
                <template slot="append">
                  <span v-show="items.unitNo == orderDetail.castUnitNo" v-for="(items, indexs) in unitList"
                    :key="indexs">
                    {{ items.symbol || items.unitName }}
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="w50p" label="换算率 :" :prop="'putInStorageList.' + index + '.exchangeRate'" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
              {
                required: true,
                message: '换算率不能为空',
                trigger: 'change',
              },
            ]">
              <el-input v-model="orderDetail.exchangeRate" clearable placeholder="请输入换算率"
                :disabled="nowChanceStau === 'check'" />
            </el-form-item>
            <el-form-item class="w50p" label="主数量/单位 :" :prop="'putInStorageList.' + index + '.primaryQuantity'" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
              { required: true, message: '数量不能为空', trigger: 'change' },
            ]">
              <el-input v-model="orderDetail.primaryQuantity" clearable disabled placeholder="主数量">
                <template slot="append">
                  <span v-show="items.unitNo == orderDetail.unitNo" v-for="(items, indexs) in unitList" :key="indexs">
                    {{ items.symbol || items.unitName }}
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="w50p" label="单价/元 :" :prop="'putInStorageList.' + index + '.price'" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
            ]">
              <el-input v-model="orderDetail.price" clearable placeholder="请输入单价"
                :disabled="nowChanceStau === 'check'" />
            </el-form-item>
            <el-form-item class="w50p" label="总金额/元 :" :prop="'putInStorageList.' + index + '.totalPrice'" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
            ]">
              <el-input v-model="orderDetail.totalPrice" clearable :disabled="nowChanceStau === 'check'"
                placeholder="请输入金额" />
            </el-form-item>

            <el-form-item class="w50p" label="生产日期 :" :prop="'putInStorageList.' + index + '.produceDate'" :rules="[
              {
                required: true,
                message: '生产日期不能为空',
                trigger: 'change',
              },
            ]">
              <el-date-picker class="w100p" v-model="orderDetail.produceDate" :picker-options="produceDate(index)"
                type="date" value-format="yyyy-MM-dd" clearable :disabled="nowChanceStau === 'check'"
                placeholder="请选择时间" />
            </el-form-item>
            <el-form-item class="w50p" label="失效日期 :" :prop="'putInStorageList.' + index + '.expirationDate'" :rules="[
              {
                required: true,
                message: '失效日期不能为空',
                trigger: 'change',
              },
            ]">
              <el-date-picker class="w100p" v-model="orderDetail.expirationDate" :picker-options="expirationDate(index)"
                type="date" value-format="yyyy-MM-dd" clearable :disabled="nowChanceStau === 'check'"
                placeholder="请选择时间" />
            </el-form-item>
            <el-form-item class="w50p" label="入库时间 :" :prop="'putInStorageList.' + index + '.intoTime'" :rules="[
              { required: true, message: '到货不能为空', trigger: 'change' },
            ]">
              <el-date-picker class="w100p" v-model="orderDetail.intoTime" :picker-options="putInDate(index)"
                type="datetime" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" clearable
                :disabled="nowChanceStau === 'check'" placeholder="请选择时间" />
            </el-form-item>
            <el-form-item class="w50p" v-if="nowChanceStau === 'check'" label="审核状态 :"
              :prop="'putInStorageList.' + index + '.forderStatus'" :rules="[
                {
                  required: true,
                  message: '审核状态不能为空',
                  trigger: 'change',
                },
              ]">
              <el-select class="w100p" v-model="orderDetail.forderStatus" placeholder="请选择审核状态" clearable filterable>
                <el-option v-for="(items, indexs) in forderStatusList" :key="indexs" :label="items.name"
                  :value="items.value" />
              </el-select>
            </el-form-item>
            <div class="btnlist">
              <div v-if="nowChanceStau === 'add' && typeFlag === 1">
                <el-button type="info" circle @click="delOrderDetail(index)">
                  <i class="el-icon-minus"></i>
                </el-button>
                <el-button type="info" circle @click="addOrderDetail">
                  <i class="el-icon-plus"></i>
                </el-button>
              </div>
            </div>
          </div>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button v-if="forderStatus === 0" class="zh-button-two" type="primary" @click="save('formData')">保
            存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script src="">
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";
import EnumSlot from "@/components/EnumSlot";

import Table from "@/components_yy/table/table.vue";
import { mymixin } from "@/utils/mixins";
import unitApi from "@/api/basic-info-manage/unit-manage"; // 单位
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage"; // 物料
import orderApi from "@/api/livestock-manage/purchaseManage/purchaseOrder"; // 订单
import orderDetailApi from "@/api/livestock-manage/purchaseManage/orderDetail"; // 订单明细
import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage"; // 仓库
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage"; // 人员
import arrivalDetailAoi from "@/api/livestock-manage/purchaseManage/arrival-detail"; // 到货明细
import putInStorage from "@/api/livestock-manage/purchaseManage/put-in-storage"; // 入库
import nowpagereqquery from "@/api/digtalOperation/production-batch-manage/create-production-batch/index";
import { mapGetters } from "vuex";
export default {
  name: "SheepInformation",
  components: {
    SearchForm,
    Table,
    MainSlot,
    TableData,
    EnumSlot,
    BtnSlot,
    Pagination,
  },
  mixins: [mymixin],
  data() {
    return {
      total: 100,
      selectIndex: 0,
      currentPage: 1,
      dataList: [],
      tableThead: [
        { isShow: true, label: "入库单号", prop: "warehousingEntryNo" },
        { isShow: true, label: "入库类型", prop: "warehousingType" },
        { isShow: true, label: "入库形式", slotName: "typeFlag" },
        { isShow: true, label: "仓库", prop: "stordocName" },
        { isShow: true, label: "入库货名", prop: "materialName" },
        { isShow: true, label: "主数量", slotName: "primaryQuantity" },
        { isShow: true, label: "应到数量", prop: "shouldArriveNum" },
        { isShow: true, label: "换算率", prop: "exchangeRate" },
        { isShow: true, label: "单价", prop: "price" },
        { isShow: true, label: "总金额", prop: "totalPrice" },
        { isShow: true, label: "入库时间", prop: "intoTime" },
        { isShow: true, label: "生产日期", prop: "produceDate" },
        { isShow: true, label: "失效日期", prop: "expirationDate" },
        { isShow: true, label: "操作", slotName: "slotOperate", width: "200" },
      ],
      btnList: ["add", "delete"],
      searchlist: {},
      tableColumn: [],
      formItemList: [
        {
          label: "入库类型",
          type: "select",
          selectOptions: [
            { text: "成品", value: "成品" },
            { text: "半成品", value: "半成品" },
            { text: "原材料", value: "原材料" },
          ],
          param: "warehousingType",
          defaultSelect: "",
          multiple: false,
          isShow: true,
        },
        {
          label: "入库单号",
          type: "input",
          param: "warehousingEntryNo",
          isShow: true,
        },
        {
          selectOptions: [
            { text: "订单入库", value: 0 },
            { text: "自行入库", value: 1 },
          ],
          label: "入库形式",
          type: "select",
          param: "typeFlag",
          defaultSelect: "",
          multiple: false,
          isShow: true,
        },
        {
          label: "入库货名",
          type: "input",
          param: "materialName",
          selectOptions: [],
          defaultSelect: "",
          multiple: false,
          isShow: true,
        },
        {
          label: "入库仓库",
          type: "input",
          param: "stordocName",
          selectOptions: [],
          defaultSelect: "",
          multiple: false,
          isShow: true,
        },
      ],
      formConfig: [
        {
          label: "入库类型",
          prop: "warehousingType",
          type: "select",
          options: [
            { name: "成品", value: "成品" },
            { name: "半成品", value: "半成品" },
            { name: "原材料", value: "原材料" },
          ],
          optionKey: { label: "name", value: "value" },
        },
        {
          label: "入库单号",
          prop: "warehousingEntryNo",
          type: "input",
        },
        {
          label: "入库形式",
          prop: "typeFlag",
          type: "select",
          options: [
            { name: "订单入库", value: 0 },
            { name: "自行入库", value: 1 },
          ],
          optionKey: { label: "name", value: "value" },
        },
        {
          label: "入库仓库",
          prop: "stordocNo",
          type: "select",
          options: [],
          optionKey: { label: "stordocName", value: "stordocNo" },
        },
        {
          label: "入库货名",
          prop: "materialNo",
          type: "select",
          options: [],
          optionKey: { label: "materialName", value: "materialNo" },
        },
      ],
      forderStatus: 0, // 审核状态
      toAdd: {},
      typeFlag: 0,
      arrivalGoodsList: [],
      selectedStaffList: [],
      personList: [],
      unitList: [],
      stordocList: [], // 仓库
      putInorderList: [], // 入库单号
      materialList: [], // 货名
      batchNoList: [], // 批次号
      warehousingTypeList: [
        { name: "成品", value: "成品" },
        { name: "半成品", value: "半成品" },
        { name: "原材料", value: "原材料" },
      ], // 入库类型
      sourceDocTypeList: [{ name: "采购", value: "采购" }],
      sourceDocNoList: [], // 所有采购订单号
      associatedDocumentTypeList: [{ name: "采购明细", value: "采购明细" }],
      associatedDocumentNoList: [], // 单个订单所有明细
      forderStatusList: [
        { name: "未审核", value: 0 },
        { name: "审核通过", value: 1 },
        { name: "审核未通过", value: 2 },
      ],
      formData: {
        sourceDocType: "采购",
        sourceDocNo: "",
        putInStorageList: [],
      },
      enumList: [
        { label: "未审核", type: 0 },
        { label: "审核通过", type: 1 },
        { label: "审核不通过", type: 2 },
      ],
      table_config: [],
      formDatalists: [
        {
          type: "input",
          prop: "warehousingEntryNo",
          selectValue: "warehousingEntryNo", // input Select Checkbox TimePicker
          typeObj: {},
          name: "入库单号",
          required: true,
        },
        {
          type: "Select",
          prop: "warehousingType",
          selectValue: "warehousingType",
          typeObj: {
            list: [
              { name: "成品", value: "成品" },
              { name: "半成品", value: "半成品" },
              { name: "原材料", value: "原材料" },
            ],
          },
          name: "入库类型",
          required: true,
        },
        {
          type: "Select",
          prop: "typeFlag",
          selectValue: "typeFlag",
          typeObj: {
            list: [
              { name: "订单入库", value: 0 },
              { name: "自行入库", value: 1 },
            ],
          },
          name: "入库形式",
          required: true,
        },
        {
          type: "Select",
          prop: "stordocName",
          selectValue: "stordocNo", // input Select Checkbox TimePicker
          typeObj: {},
          name: "仓库",
          required: true,
        },
        {
          type: "Select",
          prop: "materialName",
          selectValue: "materialNo", // input Select Checkbox TimePicker
          typeObj: {},
          name: "入库货名",
          required: true,
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "unit",
          selectValue: "unitNo",
          typeObj: {},
          name: "主数量",
          required: true,
          notSearch: true,
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "castUnit",
          selectValue: "castUnitNo",
          typeObj: {},
          name: "应到数量",
          required: true,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "exchangeRate",
          typeObj: {},
          name: "换算率",
          required: true,
        },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "shouldArriveNum",
        //   typeObj: {},
        //   name: "应到数量",
        //   required: true
        // },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "primaryQuantity",
        //   typeObj: {},
        //   name: "主数量",
        //   required: true
        // },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "price",
          typeObj: {},
          name: "单价",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalPrice",
          typeObj: {},
          name: "总金额",
          required: true,
        },
        {
          type: "date", // input Select Checkbox TimePicker
          prop: "intoTime",
          typeObj: {},
          name: "入库时间",
          required: true,
        },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "weight",
        //   typeObj: {},
        //   name: "重量/kg",
        //   required: true
        // },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "volume",
        //   typeObj: {},
        //   name: "体积/L",
        //   required: true
        // },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "packNum",
        //   typeObj: {},
        //   name: "件数",
        //   required: true
        // },
        {
          type: "date", // input Select Checkbox TimePicker
          prop: "produceDate",
          typeObj: {},
          name: "生产日期",
          required: true,
        },
        {
          type: "date", // input Select Checkbox TimePicker
          prop: "expirationDate",
          typeObj: {},
          name: "失效日期",
          required: true,
        },
      ],
      rules: {},
      selectionList: [],
    };
  },
  computed: {
    ...mapGetters(["codeList"]),
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.putInStorageList) {
          val.putInStorageList.forEach((item, index) => {
            if (item.exchangeRate && item.arriveNum) {
              this.formData.putInStorageList[index].primaryQuantity =
                item.exchangeRate * item.arriveNum;
            }
          });
        }
      },
    },
  },
  created() {
    let list = [];
    this.formDatalists.map((el) => {
      let obj = {
        prop: el.prop,
        label: el.name,
        minWidth: "140px",
      };
      if (["typeFlag", "castUnit", "unit"].includes(el.prop)) {
        obj.slotName = el.prop;
      } else if (el.name == "到货明细") {
        obj.slotName = viewList;
      }
      list.push(obj);
    });
    list.push({
      prop: "operation",
      label: "操作",
      slotName: "operation",
      width: "180",
    });
    this.tableColumn = list;

    this.getMaterialList();
    this.getstordocList();
    this.getUnitList();
    this.getOederList();
    this.getPersonList();
    this.getSourceDocNoList();
    this.toAdd = this.$route.params;
    console.log(this.toAdd);
    this.getTableDataList();
  },
  mounted() { },
  methods: {
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
      console.log(this.selectionList, "this.selectionList");
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getTableDataList();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getTableDataList();
    },
    putInDate(index) {
      if (!typeof index === "number") return null;
      const self = this;
      // 入库
      return {
        disabledDate(time) {
          if (self.formData.putInStorageList[index].produceDate) {
            //  如果结束时间不为空，则小于结束时间
            return (
              new Date(
                self.formData.putInStorageList[index].produceDate
              ).getTime() >= time.getTime()
            );
          } else {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
            return null;
          }
        },
      };
    },
    // 限制前面日期不能低于后面日期
    produceDate(index) {
      if (!typeof index === "number") return null;
      const self = this;
      // 生产日期
      return {
        disabledDate(time) {
          if (
            self.formData.putInStorageList[index].expirationDate &&
            self.formData.putInStorageList[index].intoTime
          ) {
            let a = new Date(
              self.formData.putInStorageList[index].expirationDate
            ).getTime();
            let b = new Date(
              self.formData.putInStorageList[index].intoTime
            ).getTime();
            return a > b ? b <= time.getTime() : a <= time.getTime();
          } else if (self.formData.putInStorageList[index].expirationDate) {
            return (
              new Date(
                self.formData.putInStorageList[index].expirationDate
              ).getTime() <= time.getTime()
            );
          } else if (self.formData.putInStorageList[index].intoTime) {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
            return (
              new Date(
                self.formData.putInStorageList[index].intoTime
              ).getTime() <= time.getTime()
            );
          } else {
            return null;
          }
        },
      };
    },
    expirationDate(index) {
      if (!typeof index === "number") return null;
      // 失效日期
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.putInStorageList[index].produceDate) {
            //  如果开始时间不为空，则结束时间大于开始时间
            self.time = new Date();
            return (
              new Date(
                self.formData.putInStorageList[index].produceDate
              ).getTime() >= time.getTime()
            );
          } else {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
            return null;
          }
        },
      };
    },
    arrivalToputin() {
      arrivalDetailAoi
        .queryListByOrderNo(this.toAdd.arriveOrderNo)
        .then((res) => {
          if (res.code === 1) {
            // this.formData.sourceDocType = "采购";
            this.$set(this.formData, "sourceDocType", "采购");
            this.formData.sourceDocNo = res.data[0].orderNo;
            this.$set(this.formData, "arrivalGoodsList", []);
            this.arrivalGoodsList = res.data;
            this.$set(this.formData, "arrivalGoodsList", res.data);
            this.chooseGoods(res.data);
          }
        });
      this.nowChanceStau = "add";
      this.titleText = "添加入库";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    // 获取源头单号
    getSourceDocNoList() {
      orderApi.conditionQuery({ forderStatus: 1 }).then((res) => {
        if (res.code === 1) {
          this.sourceDocNoList = res.data;
        }
      });
    },
    // 添加一个入库单
    addOrderDetail() {
      // 获取入库订单编号
      nowpagereqquery.addcode("WAREHOUSING_ENTRY").then((res) => {
        this.$set(this.formData, "putInStorageList", []);
        this.$set(this.formData.putInStorageList, 0, [
          {
            typeFlag: this.typeFlag,
            warehousingType: "",
            stordocNo: "",
            materialNo: "",
            batchNo: "",
            lotNumber: "",
            primaryQuantity: "",
            unitNo: "",
            arriveNum: "",
            castUnitNo: "",
            exchangeRate: "",
            shouldArriveNum: "",
            price: "",
            totalPrice: "",
            intoTime: "",
            sourceDocType: "采购",
            sourceDocNo: "",
            associatedDocumentType: "采购明细",
            assassociatedDocumentNo: "",
            weight: "",
            volume: "",
            packNum: "",
            produceDate: "",
            expirationDate: "",
            forderStatus: 0,
            organizationNo: sessionStorage.organizationNo,
            key: Date.now(),
            warehousingEntryNo: res.data,
          },
        ]);
      });
    },
    // 删除一个入库单
    delOrderDetail(index) {
      console.log(this.formData.putInStorageList);
      if (this.formData.putInStorageList.length === 1) {
        return;
      } else {
        this.formData.putInStorageList.splice(index, 1);
      }
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      console.log(enumInfo);
      this.selectIndex = enumInfo.index || 0;
      if (this.selectIndex === 0) {
        this.addActive = true;
      } else {
        this.addActive = false;
      }
      this.currentPage = 1;
      this.forderStatus = this.selectIndex;
      this.search();
    },
    // 获取所有物料
    getMaterialList() {
      materialApi.getqueryList({}).then((res) => {
        if (res.code === 1) {
          this.materialList = res.data.filter(item => {
            return !!item.unitNo
          });
          this.$set(this.formDatalists[4], "typeObj", {
            list: res.data,
            listName: ["materialName", "materialNo"],
          });
          this.setOptions(this.formConfig, "materialNo", res.data);
        }
      });
    },
    // 获取人员列表
    getPersonList() {
      personApi.getStaffListByCondition().then((res) => {
        if (res.code === 1) {
          this.personList = res.data;
          let list = [];
          res.data.forEach((item) => {
            list.push({
              name: item.person.name,
              value: item.personNo,
            });
          });
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "receiverName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    // 获取所有订单
    getOederList() {
      orderApi
        .conditionQuery({ completeStatus: false, forderStatus: 1 })
        .then((res) => {
          if (res.code === 1) {
            let list = [];
            res.data.forEach((item) => {
              list.push({
                name: item.orderNo,
                value: item.orderNo,
              });
            });
            this.formDatalists.forEach((item, index) => {
              if (item.prop === "orderNo") {
                this.$set(this.formDatalists[index].typeObj, "list", list);
              }
            });
            this.formDatalists.forEach((item, index) => {
              if (item.prop === "personName") {
                this.$set(this.formDatalists[index].typeObj, "list", list);
              }
            });
          }
        });
    },
    // 获取仓库
    getstordocList() {
      warehouseApi.conditionQuery({}).then((res) => {
        if (res.code === 1) {
          this.stordocList = res.data;
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "stordocName") {
              this.$set(this.formDatalists[index], "typeObj", {
                list: res.data,
                listName: ["stordocName", "stordocNo"],
              });
            }
          });
          this.setOptions(this.formConfig, "stordocNo", res.data);
        }
      });
    },
    // 获取单位列表X
    getUnitList() {
      unitApi.getPlantingUnitListByCondition({}).then((res) => {
        if (res.code === 1) this.unitList = res.data;
      });
    },
    timeEvent(event, prop) {
      if (prop === "arriveTime") {
        this.formData.putInStorageList.forEach((item, index) => {
          this.$set(this.formData.putInStorageList[index], "arriveTime", event);
        });
      }
    },
    // 获取单个商品
    getGoods(event, index) {
      materialApi.getqueryList({ materialNo: event }).then((res) => {
        this.$set(
          this.formData.putInStorageList[index],
          "unitNo",
          res.data[0].unitNo
        );
        this.$set(
          this.formData.putInStorageList[index],
          "castUnitNo",
          res.data[0].unitNo
        );
      });
    },
    // 选择到货商品
    chooseGoods(e) {
      this.$set(this.formData, "putInStorageList", e);
      this.formData.arrivalGoodsList[0].warehousingEntryNo =
        this.warehousingEntryNo;
      this.formData.putInStorageList.forEach((item, index) => {
        this.formData.putInStorageList[index].sourceDocType =
          this.formData.sourceDocType;
        this.formData.putInStorageList[index].sourceDocNo =
          this.formData.sourceDocNo;
        this.formData.putInStorageList[index].associatedDocumentType =
          this.formData.sourceDocType + "明细";
        this.formData.putInStorageList[index].associatedDocumentNo =
          item.orderDetailNo;
        this.$set(
          this.formData.putInStorageList[index],
          "shouldArriveNum",
          item.confirmQuantity || item.shouldArriveNum
        );
        this.$set(this.formData.putInStorageList[index], "forderStatus", 0);
        this.formData.putInStorageList[index].key = Date.now();
        this.formData.putInStorageList[index].typeFlag = this.typeFlag;
      });
    },
    // 获取订单详细列表
    getOrderDetailList(e) {
      orderDetailApi.numberQuery(e).then((res) => {
        if (res.code === 1) {
          this.$set(this.formData, "arrivalGoodsList", []);
          this.arrivalGoodsList = res.data;
          this.$set(this.formData, "arrivalGoodsList", [
            this.arrivalGoodsList[0],
          ]);
          this.chooseGoods([this.arrivalGoodsList[0]]);
        }
      });
    },
    getTableDataList() {
      this.loading = false;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        organizationNo: sessionStorage.organizationNo,
        breedTypeNo: sessionStorage.breedTypeNo,
        entity: {
          forderStatus: this.forderStatus,
          ...this.searchlist,
        },
      };
      delete params.entity.intoTime;
      putInStorage.pageQuery(params).then((res) => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          console.log(this.dataList)
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.getTableDataList();
          }
          if (this.toAdd.isTo === "toAdd") {
            this.arrivalToputin();
          }
          this.toAdd = {};
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.warehousingEntryNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      putInStorage
        .numberBatchDel({ noList: this.selectedStaffList })
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(list) {
      let selectedStaffList = [];
      list.forEach((item) => {
        selectedStaffList.push(item.warehousingEntryNo);
      });
      console.log(selectedStaffList, list, "selectedStaffList");
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          putInStorage
            .numberBatchDel({ noList: selectedStaffList })
            .then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.search();
              } else {
                this.$message.warning(res.msg || "删除失败");
              }
            });
        })
        .catch(() => { });
    },
    changeAddWays(e) {
      this.typeFlag = e;
      if (this.typeFlag === 0) {
        this.formData = {
          sourceDocNo: "",
          sourceDocType: "采购",
          putInStorageList: [],
        };
      }
      if (this.typeFlag === 1) {
        this.formData = {
          putInStorageList: [
            {
              typeFlag: this.typeFlag,
              warehousingType: "",
              stordocNo: "",
              materialNo: "",
              batchNo: "",
              lotNumber: "",
              primaryQuantity: "",
              unitNo: "",
              arriveNum: "",
              castUnitNo: "",
              exchangeRate: "",
              shouldArriveNum: "",
              price: "",
              totalPrice: "",
              intoTime: "",
              weight: "",
              volume: "",
              packNum: "",
              produceDate: "",
              expirationDate: "",
              forderStatus: 0,
              organizationNo: sessionStorage.organizationNo,
              key: Date.now(),
            },
          ],
        };
      }
      // 获取入库订单编号
      nowpagereqquery.addcode("WAREHOUSING_ENTRY").then((res) => {
        this.warehousingEntryNo = res.data;
        this.typeFlag === 1 &&
          (this.formData.putInStorageList[0].warehousingEntryNo = res.data);
      });
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        if (this.forderStatus === 0) {
          this.add();
        } else {
          this.$message.warning("请切换至未审核！");
        }
      } else if (flag == "delete") {
        if (this.selectionList.length > 0) {
          this.handleDelete(this.selectionList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
      this.addEditFlag = flag;
    },
    add() {
      this.formData.putInStorageList = [];
      this.arrivalGoodsList = [];
      if (this.typeFlag === 0) {
        this.formData = {
          sourceDocNo: "",
          sourceDocType: "采购",
          putInStorageList: [],
        };
      }
      if (this.typeFlag === 1) {
        this.formData = {
          putInStorageList: [
            {
              typeFlag: this.typeFlag,
              warehousingType: "",
              stordocNo: "",
              materialNo: "",
              batchNo: "",
              lotNumber: "",
              primaryQuantity: "",
              unitNo: "",
              arriveNum: "",
              castUnitNo: "",
              exchangeRate: "",
              shouldArriveNum: "",
              price: "",
              totalPrice: "",
              intoTime: "",
              weight: "",
              volume: "",
              packNum: "",
              produceDate: "",
              expirationDate: "",
              forderStatus: 0,
              organizationNo: sessionStorage.organizationNo,
              key: Date.now(),
            },
          ],
        };
      }
      // 获取入库订单编号
      nowpagereqquery
        .addcode("WAREHOUSING_ENTRY")
        .then((res) => {
          this.warehousingEntryNo = res.data;
        })
        .catch((err) => {
          this.$message.warning(err);
        });
      console.log(this.formData);
      this.nowChanceStau = "add";
      this.titleText = "添加入库";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row, e) {
      this.typeFlag = row.typeFlag;
      this.$set(this.formData, "putInStorageList", [
        { key: Date.now(), ...row },
      ]);
      this.nowChanceStau = e;
      let a = e === "check" ? "审核" : "修改入库";
      this.titleText = a;
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    kookInfo(e) {
      this.formData = {};
      arrivalDetailAoi.queryListByOrderNo(e).then((res) => {
        if (res.code === 1) {
          this.$set(this.formData, "putInStorageList", res.data);
        }
      });
      this.nowChanceStau = "kookInfo";
      this.titleText = "查看到货明细";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    addDetail(e, index) {
      let validateFieldList = [];
      this.$refs["formData"].validateField(
        [
          "putInStorageList." + index + ".materialNo",
          "putInStorageList." + index + ".confirmQuantity",
          "putInStorageList." + index + ".castUnitNo",
          "putInStorageList." + index + ".unitNo",
          "putInStorageList." + index + ".exchangeRate",
          "putInStorageList." + index + ".primaryQuantity",
          "putInStorageList." + index + ".price",
          "putInStorageList." + index + ".packNum",
          "putInStorageList." + index + ".totalPrice",
          "putInStorageList." + index + ".address",
        ],
        (valid) => {
          if (!valid) {
            validateFieldList.push(valid);

            // 因为我这里总共校验了三个字段,所有最终三个字段都校验成功之后,数组中会有三个""
            if (
              validateFieldList.length === 10 &&
              validateFieldList.every((item) => item === "")
            ) {
              orderDetailApi.add(e).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  orderDetailApi.numberQuery(e.orderNo).then((res) => {
                    this.$set(this.formData, "putInStorageList", res.data);
                  });
                } else {
                  this.$message.warning(res.msg || "添加失败");
                }
              });
            }
            // 校验不通过走这里
            return;
          } else {
            return false;
          }
        }
      );
    },
    editDetail(e) {
      this.$confirm("确定修改该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          orderDetailApi.edit(e).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.warning(res.msg || "修改失败");
            }
          });
        })
        .catch(() => { });
    },
    delDetial(e, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          orderDetailApi.numberQuery(e.orderNo).then((res) => {
            if (res.data.length <= 1) {
              this.$message.warning("已是最后一条数据禁止删除");
            } else {
              orderDetailApi.numberDel(e.orderDetailNo).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.formData.putInStorageList.splice(index, 1);
                } else {
                  this.$message.warning(res.msg || "删除失败");
                }
              });
            }
          });
        })
        .catch(() => { });
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          // 添加仓库名称
          this.formData.putInStorageList.forEach((item, index) => {
            if (item.stordocNo) {
              this.stordocList.forEach((item1) => {
                if (item1.stordocNo === item.stordocNo) {
                  this.formData.putInStorageList[index].stordocName =
                    item1.stordocName;
                }
              });
            }
          });
          if (this.nowChanceStau === "edit") {
            putInStorage.edit(this.formData.putInStorageList[0]).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            console.log(this.formData.putInStorageList);
            this.formData.putInStorageList = this.formData.putInStorageList.map(item => {
              return {
                ...item,
                systemNo: sessionStorage.systemNo
              }
            })
            putInStorage
              .batchAdd(this.formData.putInStorageList)
              .then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg || "新增成功！");
                  this.dialogFormVisible = false;
                  this.search();
                  this.$refs[formData].resetFields();
                } else {
                  this.$message.error(res.msg || "新增失败！");
                }
              });
          } else if (this.nowChanceStau === "check") {
            putInStorage
              .check(this.formData.putInStorageList[0])
              .then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg || "审核成功！");
                  this.dialogFormVisible = false;
                  this.search();
                  this.$refs[formData].resetFields();
                } else {
                  this.$message.error(res.msg || "审核失败！");
                }
              });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";

.addone {
  margin-left: 140px;
}

.zhu {
  display: flex;

  ::v-deep .el-input__inner {
    background-color: rgb(241, 239, 239) !important;
  }
}

.numberUnit {
  display: flex;

  .one {
    width: 75%;
  }

  .two {
    width: 25%;
  }
}

.orderDetail {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;

  .w50p {
    padding: 0 5px;
  }
}

.btnlist {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

.goods {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 10px;
}
</style>
